from django.core.cache import caches
from django.http import JsonResponse
from django.shortcuts import render

from django.conf import settings

from goods.models import SKU
from utils.baseview import BaseView

# Create your views here.

CARTS_CACHE = caches["carts"]

class CartsView(BaseView):
    def post(self,request,username):
        """
        添加购物车视图逻辑
        1.获取请求体数据[sku_id count]
        2.存入redis数据库
        3.组织数据返回
        """
        data = request.data
        sku_id = data.get("sku_id")
        count = data.get("count")
        #取出该用户现有购物车数据并进行合并
        user = request.myuser
        cache_key = self.get_cache_key(user.id)
        carts_data = self.get_carts_all_data(cache_key)
        if sku_id not in carts_data:
            carts_data[sku_id] = [count,1]
        else:
            new_count = int(carts_data[sku_id][0]) + int(count)
            carts_data[sku_id][0] = new_count
        #更新redis数据
        CARTS_CACHE.set(cache_key,carts_data)
        result = {
            'code': 200,
            'data':
                {
                    'carts_count': len(carts_data)
                },
            'base_url': settings.PIC_URL
        }
        return JsonResponse(result)

    def get(self,request,username):
        """
        查询购物车的视图逻辑
        1.先获取redis中数据[sku_id]
        2.获取mysql中数据
        3.组织数据返回
        """
        user = request.myuser
        sku_list = self.get_sku_list(user)
        result = {
            "code":200,
            "data":sku_list,
            "base_url":settings.PIC_URL
        }

        return JsonResponse(result)


    def get_cache_key(self,user_id):
        """
        功能函数：生成redis中的key
        """
        return "carts_%s" % user_id

    def get_carts_all_data(self, cache_key):
        """
        功能函数：获取购物车的所有数据
        :return: {} 或者 {"1":[5,0]}
        """
        data = CARTS_CACHE.get(cache_key)
        if not data:
            return {}
        return data

    def merge_carts(self,offline_data,user_id):
        """
        功能函数：合并购物车数据
        :param offline_data:离线购物车数据
        :return: 合并后购物车中商品种类数量
        """
        key = self.get_cache_key(user_id)
        carts_data = self.get_carts_all_data(key)

        # 离线购物车无数据情况
        if not offline_data:
            return len(carts_data)

        for sku_dict in offline_data:
            sku_id = sku_dict.get('id')
            count = int(sku_dict.get('count'))
            if sku_id not in carts_data:
                carts_data[sku_id] = [count,1]
            else:
                new_count = count + carts_data[sku_id][0]
                carts_data[sku_id][0] = new_count

        #更新到redis
        CARTS_CACHE.set(key,carts_data)

        return len(carts_data)

    def get_sku_list(self, user):
        """
        功能函数：订单确认页商品数据展示
        :param user: 用户对象
        :return: sku_list [{},{}.......]
        """
        key = self.get_cache_key(user.id)
        carts_data = self.get_carts_all_data(key)
        all_sku_id = carts_data.keys()
        skus = SKU.objects.filter(id__in=all_sku_id)  # id__in 双下划线
        data_list = []

        for sku in skus:
            sale_query = sku.sale_attr_value.all()
            data = {
                "id": sku.id,
                "count": carts_data[str(sku.id)][0],
                "selected": carts_data[str(sku.id)][1],
                "price": sku.price,
                "name": sku.name,
                "default_image_url": str(sku.default_image_url),
                "sku_sale_attr_name": [i.spu_sale_attr.name for i in sale_query],  # 销售属性名
                "sku_sale_attr_val": [i.name for i in sale_query]  # 销售属性值
            }
            data_list.append(data)

        return data_list







